package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handleException(SQLIntegrityConstraintViolationException exception){
        log.error(exception.getMessage(), exception);
        String message = exception.getMessage();
        //判定当前异常信息中是否包含 Duplicate entry
        if(exception.getMessage().contains("Duplicate entry")){
            //如果包含, 截取字符串 .
            String errorMsg = exception.getMessage().split(" ")[2];
            return R.error(errorMsg+" 已存在!");
        }
        return R.error("对不起, 此次操作失败!");
    }


    @ExceptionHandler(CustomException.class)
    public R hanleException(CustomException exception){
        log.error(exception.getMessage(), exception);
        String message = exception.getMessage();
        return R.error(message);
    }

}
